﻿using EONFULLSIN2.Common;
using EONFULLSIN2.Core;
using EONFULLSIN2.Core.Helpers;
using EONFULLSIN2.Core.Utils;
using EONFULLSIN2.Services.ControlService;
using EONFULLSIN2.Services.DB;
using EONFULLSIN2.Services.Device.DIOModelA;
using EONFULLSIN2.Services.Device.DIOModelB;
using EONFULLSIN2.Services.Device.JuYing;
using EONFULLSIN2.Services.Device.ZhongChuangZhiHe;
using EONFULLSIN2.Services.Device.ZhuoLan;
using EONFULLSIN2.Services.Device.ZMoiton;
using EONFULLSIN2.Services.Message;
using EONFULLSIN2.View;
using EONFULLSIN2.ViewModel;
using HandyControl.Data;
using HandyControl.Properties.Langs;
using HandyControl.Tools;
using Prism.DryIoc;
using Prism.Ioc;
using Prism.Services.Dialogs;
using System.Configuration;
using System.Data;
using System.Globalization;
using System.Resources;
using System.Security.Cryptography;
using System.Windows;

namespace EONFULLSIN2;

/// <summary>
/// App.xaml 的交互逻辑
/// </summary>
public partial class App : PrismApplication
{
    protected override Window CreateShell()
    {
        //UI线程未捕获异常处理事件
        App.Current.DispatcherUnhandledException += Current_DispatcherUnhandledException;
        //非UI线程未捕获异常处理事件(例如自己创建的一个子线程) App.config中加了legacyUnhandledExceptionPolicy 则不会进
        AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
        //Task线程内未捕获异常处理事件
        TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
        //防止系统休眠
        WinSleepHelper.PreventForCurrentThread();

        return Container.Resolve<MainWindow>();
    }


    protected override void RegisterTypes(IContainerRegistry containerRegistry)
    {
        #region 注册服务
        containerRegistry.RegisterSingleton<IMessageService, MessageService>();

        //DB部分Service
        containerRegistry.RegisterSingleton<IFreeSqlMainContext, FreeSqlMainContext>();
        containerRegistry.RegisterSingleton<IFreeSqlHisContext, FreeSqlHisContext>();
        containerRegistry.RegisterSingleton<IDbOperate<IFreeSqlMainContext>, DbOperate<IFreeSqlMainContext>>();
        containerRegistry.RegisterSingleton<IDbOperate<IFreeSqlHisContext>, DbOperate<IFreeSqlHisContext>>();

        //通信部分Service
        containerRegistry.RegisterSingleton<IJuYingModbusService, JuYingModbusService>();
        containerRegistry.RegisterSingleton<IZhuoLanModbusService, ZhuoLanModbusService>();
        //containerRegistry.RegisterSingleton<IAdamComDIOModelAService, AdamComDIOModelAService>();
        //containerRegistry.RegisterSingleton<IAdamComDIOModelBService, AdamComDIOModelBService>();
        containerRegistry.RegisterSingleton<IZMoitonService, ZMoitonService>();
        containerRegistry.RegisterSingleton<IZczhModbusService, ZczhModbusService>();

        //温度启动部分Service
        containerRegistry.RegisterSingleton<ITempNegative80Service, TempNegative80Service>();
        #endregion

        #region 导航
        //主程序
        containerRegistry.RegisterForNavigation<MainWindow, MainWindowModel>(nameof(MainWindow));
        //主页面
        containerRegistry.RegisterForNavigation<MainView, MainViewModel>(nameof(MainView));
        //设备操作
        containerRegistry.RegisterForNavigation<DeviceOperationView, DeviceOperationViewModel>(nameof(DeviceOperationView));
        //数据采集
        containerRegistry.RegisterForNavigation<DeviceManagerView, DeviceManagerViewModel>(nameof(DeviceManagerView));
        //设备控制
        containerRegistry.RegisterForNavigation<DeviceControlView, DeviceControlViewModel>(nameof(DeviceControlView));
        //数据追溯
        containerRegistry.RegisterForNavigation<DataHistoryView, DataHistoryViewModel>(nameof(DataHistoryView));
        //系统管理
        containerRegistry.RegisterForNavigation<SystemManagerView, SystemManagerViewModel>(nameof(SystemManagerView));
        #endregion

        #region 弹框
        //登录
        containerRegistry.RegisterDialog<LoginView, LoginViewModel>(nameof(LoginView));

        #endregion
    }


    protected override void OnInitialized()
    {
        
#if DEBUG
        DBHelper.CraeteData();
#endif

        //设置系统语言&皮肤
        AppInfo.InitAppConfig();

        //设置默认语言
        //GlobalData.Config.Lang = "en";
        //UpdateLang(GlobalData.Config.Lang);

        #region Login
        PrismIocInfo.DialogService.ShowDialog(nameof(LoginView), new DialogParameters() { { "Title", "EONFULLSIN" } }, rhs =>
        {
            if (rhs.Result != ButtonResult.OK) {
                WinSleepHelper.RestoreForCurrentThread();
                Environment.Exit(0);
            }
        });
        #endregion


        base.OnInitialized();
    }


    protected override void OnExit(ExitEventArgs e)
    {
        //连接资源释放
        var juYingModbusService = PrismIocInfo.GetInstanceByIoc<IJuYingModbusService>();
        juYingModbusService.DisConnectAsync();

        var zhuoLanModbusService = PrismIocInfo.GetInstanceByIoc<IZhuoLanModbusService>();
        zhuoLanModbusService.DisConnectAsync();

        //var adamComDIOModelAService = PrismIocInfo.GetInstanceByIoc<IAdamComDIOModelAService>();
        //var adamComDIOModelBService = PrismIocInfo.GetInstanceByIoc<IAdamComDIOModelBService>();
        //adamComDIOModelAService.StopReadDOChannelStatusAsync();
        //adamComDIOModelAService.CloseComAsync();
        //adamComDIOModelBService.StopReadDOChannelStatusAsync();
        //adamComDIOModelBService.CloseComAsync();
        var zMoitonService = PrismIocInfo.GetInstanceByIoc<IZMoitonService>();
        zMoitonService.DisConnectAsync();

        var zczhModbusService = PrismIocInfo.GetInstanceByIoc<IZczhModbusService>();
        zczhModbusService.DisConnectAsync();

        //调用基类的 OnExit 方法来执行默认退出逻辑
        base.OnExit(e);
       
        //显式调用 Shutdown，如果需要强制退出
        //Application.Current.Shutdown();
    }

    #region 异常处理
    private void Current_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
    {
        LogManager.Error("UI线程内未捕获异常处理事件", e.Exception);
        try
        {
            e.Handled = true; //把 Handled 属性设为true，表示此异常已处理，程序可以继续运行，不会强制退出
        }
        catch (Exception ex)
        {
            LogManager.Error("UI线程内未捕获异常处理事件catch", ex);
        }
    }

    private void TaskScheduler_UnobservedTaskException(object? sender, UnobservedTaskExceptionEventArgs e)
    {
        if (e.Exception is Exception exception)
        {
            LogManager.Error("Task线程内未捕获异常处理事件", exception);
        }
        //e.SetObserved();//设置该异常已察觉（这样处理后就不会引起程序崩溃）
    }


    private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
    {
        if (e.ExceptionObject is Exception exception)
        {
            LogManager.Error("非UI线程未捕获异常处理事件", exception);
        }
    }
    #endregion
}


